package org.swift.mashup.engine.model;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.axiom.attachments.utils.IOUtils;

public class InputStreamActivityContext implements ActivityContext {
	
	private final InputStream stream;
	private long size;
	private boolean bytesHaveBeenRead = false;
			
	public InputStreamActivityContext(InputStream stream, long size) {
		this.stream = stream;
		this.size = size;
	}
	
	@Override
	public byte[] getBytes() throws IOException {
		if ( this.bytesHaveBeenRead ) {
			final String err = "bytes for this stream have already been read";
			if ( stream.markSupported() ) {
				try {
					stream.reset();
					this.bytesHaveBeenRead = false;
				}
				catch (IOException e) {
					throw new RuntimeException(err);
				}
			}
			else {
				throw new RuntimeException(err);
			}
		}

		this.bytesHaveBeenRead = true;
		return IOUtils.getStreamAsByteArray(stream);
	}

	@Override
	public long getSize() {
		return size;
	}
	
	public void writeAll(OutputStream stream) throws IOException {
		byte[] buffer = new byte[1024];
		int length = 0;
		while ((length = this.stream.read(buffer)) != -1) {
			stream.write(buffer, 0, length);
		}
	}

	@Override
	public Object getValue() {
		return this.stream;
	}
	
	

}
